// 登录页面
import React, {useState, useRef, useEffect} from 'react';
import {Navigation} from 'react-native-navigation';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  KeyboardAvoidingView,
  Platform,
  Alert,
} from 'react-native';

import storage, {save, load, remove} from './../../storage/storage';
import config from './../../storage/config';

// 主根的路由,修改配置后，重启项目（坑死了）
const mainRoot = {
  root: {
    stack: {
      children: [
        {
          component: {
            name: 'SearchProduct',
          },
        },
      ],
    },
    bottomTabs: {
      children: [
        {
          stack: {
            children: [
              {
                component: {
                  name: 'Home',
                },
              },
            ],
          },
        },
        {
          stack: {
            children: [
              {
                component: {
                  name: 'Product',
                },
              },
            ],
          },
        },
        {
          stack: {
            children: [
              {
                component: {
                  name: 'My',
                },
              },
            ],
          },
        },
      ],
    },
  },
};
// const styles = StyleSheet.create({
//   root: {
//     flex: 1,
//     alignItems: 'center',
//     justifyContent: 'center',
//     backgroundColor: 'whitesmoke',
//   },

// });

const Login = () => {
  const [userName, setUserName] = useState('wqw');
  const [passWord, setPassWrod] = useState('123456');
  const elmPassword = useRef();

  const onLogin = async () => {
    if (userName.trim().length != 0 && passWord.trim().length != 0) {
      // let result = await config.userLogin({userName, passWord});
      // console.log(result);
      // // 存储本地数据：
      // await save('loginState', result);
      Navigation.setRoot(mainRoot);
    } else {
      // 弹出信息框
      Alert.alert(
        '提示',
        '请输入账号和密码！',
        [
          {
            text: '确定',
          },
        ],
        {cancelable: true},
      );
      //   return;
    }
  };

  // 判断是否登录过
  useEffect(() => {
    // console.log('--------判断是否登录过--------------');
    load('loginState', checkLoginState);
  });

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS != 'ios' ? 'padding' : 'height'}
      style={styles.container}>
      <View>
        <Text style={styles.title}>登录</Text>
      </View>
      <KeyboardAvoidingView style={styles.inputContainer}>
        <TextInput
          value={userName}
          placeholder="请输入账号"
          style={styles.inputs}
          underlineColorAndroid="transparent"
          clearTextOnFocus={true}
          textContentType="username"
          onChangeText={text => setUserName(text)}
          onSubmitEditing={() => elmPassword && elmPassword.current.focus()}
        />
      </KeyboardAvoidingView>
      <KeyboardAvoidingView style={styles.inputContainer}>
        <TextInput
          ref={elmPassword}
          value={passWord}
          placeholder="请输入8位密码"
          style={styles.inputs}
          underlineColorAndroid="transparent"
          secureTextEntry={true}
          maxLength={8}
          onChangeText={text => setPassWrod(text)}
        />
      </KeyboardAvoidingView>
      <TouchableHighlight
        style={[styles.buttonContainer, styles.loginButton]}
        activeOpacity={0.9}
        onPress={() => onLogin()}>
        <Text style={styles.loginText}>登录</Text>
      </TouchableHighlight>
    </KeyboardAvoidingView>

    // <View style={styles.root}>
    //   <Button
    //     title="Login"
    //     color="#710ce3"
    //     onPress={() => Navigation.setRoot(mainRoot)}
    //   />
    // </View>
  );
};

export default Login;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    paddingTop: 100,
  },
  inputContainer: {
    borderBottomColor: '#a1d5ec',
    borderRadius: 0,
    borderBottomWidth: 1,
    width: 250,
    height: 45,
    marginBottom: 20,
    flexDirection: 'row',
    alignItems: 'center',
  },
  inputs: {
    height: 45,
    // marginLeft:16,
    borderBottomColor: '#00b5ec',
    flex: 1,
  },
  buttonContainer: {
    height: 45,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: 250,
    borderRadius: 5,
    marginTop: 40,
  },
  loginButton: {
    backgroundColor: '#00b5ec',
  },
  loginText: {
    color: 'white',
  },
  title: {
    fontSize: 20,
    marginBottom: 60,
    color: '#00b5ec',
  },
});

// 判断是否登录
const checkLoginState = obj => {
  // console.log('--=-==-==----', obj);
  // 跳过登录页
  if (typeof obj === 'object') {
    // console.log('=========================', obj);
    Navigation.setRoot(mainRoot);
  } else if (obj === false) {
    console.log('需要登录,渲染登录页面');
  }
};
